﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.Collections;
using System.Data.OracleClient;
using Business.FlowOperation;
using WF_DataAccess;
using Common;
using WF_Business;

namespace Business.OfficialDoc
{
    /// <!--
    /// 功能描述  : 获取工作流相关数据
    /// 创建人  : QiuXiaoChi
    /// 创建时间: 2013-08-27
    /// -->
    public class OfficialDocHandler
    {

        private static OfficialDocHandler _officialdocInstance;

        private OfficialDocHandler()
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static OfficialDocHandler getInstance()
        {
            if (_officialdocInstance == null)
            {
                _officialdocInstance = new OfficialDocHandler();
            }
            return _officialdocInstance;
        }

        /// <summary>
        /// 获取用户有权限启动的流程
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public DataSet GetStartFlowByUserid(string userid, string type)
        {
            DataTable dt = WorkFlowHandle.GetStartWorkflow(userid, type);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);
            return ds;
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        public DataSet GetWorkItemList(string loginName)
        {
            DataTable dtWorkItem = WorkFlowHandle.GetWorkItemSearchList(loginName, " status='1'");
            DataSet ds = new DataSet();
            ds.Tables.Add(dtWorkItem);
            return ds;
        }

        /// <summary>
        /// 获取待办列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <returns></returns>
        public string GetWorkItemListJson(string loginName)
        {
            DataTable dtWorkItem = WorkFlowHandle.GetWorkItemSearchList(loginName, " status='1'");
            JsonOperation joTemp = new JsonOperation();
            return joTemp.BindJson(dtWorkItem);
            //return JsonOperation.DataTableToJson(dtWorkItem);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="searchSql">查询条件</param>
        /// <returns></returns>
        public string GetWorkItemSearchListCount(string loginName, string searchSql)
        {
            if (String.IsNullOrEmpty(searchSql))
            {
                searchSql = "1 = 1";
            }
            //else
            //{
            //    searchSql = "SUBITEM_TYPE_NAME = '" + searchSql + "'";
            //}
            DataTable dtWorkItem = WorkFlowHandle.GetWorkItemSearchList(loginName, searchSql);

            string result = "{Result:'True',Count:" + dtWorkItem.Rows.Count + "}";
            return result;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="searchSql">查询条件</param>
        /// <returns></returns>
        public string GetWorkItemSearchListJson(string loginName, string searchSql)
        {
            DataTable dtWorkItem = WorkFlowHandle.GetWorkItemSearchList(loginName, searchSql);
            JsonOperation joTemp = new JsonOperation();
            return joTemp.BindJson(dtWorkItem);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="searchSql">查询条件</param>
        /// <returns></returns>
        public string GetAllWorkItemSearchListJson(string loginName, string searchSql, string official_recordnum)
        {
            DataTable dtWorkItem = WorkFlowHandle.GetAllWorkItemSearchList(loginName, searchSql);
            DataTable dtResult = dtWorkItem.Clone();
            try
            {
                int recordnum = int.Parse(official_recordnum);
                int recordnum_tonum = int.Parse(official_recordnum) + 20;
                for (int i = 0; i < dtWorkItem.Rows.Count; i++)
                {
                    if (i >= recordnum_tonum)
                    {
                        break;
                    }
                    if (i >= recordnum && i < recordnum_tonum)
                    {
                        dtResult.ImportRow(dtWorkItem.Rows[i]);
                    }

                }
                return JsonOperation.DataTableToJson(dtResult);
            }
            catch
            {
            }

            return JsonOperation.DataTableToJson(dtResult);
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="loginName">登录名</param>
        /// <param name="searchSql">查询条件</param>
        ///  <param name="official_recordnum">记录数</param>
        /// <returns></returns>
        public string GetWorkItemSearchListJson(string loginName, string searchSql, string official_recordnum)
        {
            DataTable dtWorkItem = WorkFlowHandle.GetWorkItemSearchList(loginName, searchSql);
            DataTable dtResult = dtWorkItem.Clone();
            try
            {
                int recordnum = int.Parse(official_recordnum);
                int recordnum_tonum = int.Parse(official_recordnum) + 20;
                for (int i = 0; i < dtWorkItem.Rows.Count; i++)
                {
                    if (i >= recordnum && i < recordnum_tonum)
                    {
                        dtResult.ImportRow(dtWorkItem.Rows[i]);
                    }
                }
                return JsonOperation.DataTableToJson(dtResult);
            }
            catch
            {
            }
            return JsonOperation.DataTableToJson(dtWorkItem);
        }

      
        /// <summary>
        /// 获取待办任务汇总
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public DataSet GetWorkItemCollect(string loginName)
        {
            DataTable dtTemp = WorkFlowHandle.GetWorkItemCollect(loginName);
            DataSet ds = new DataSet();
            ds.Tables.Add(dtTemp);
            return ds;
        }

        /// <summary>
        /// 获取节点上的资源树
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="wiid">节点编号</param>
        /// <param name="step">节点名称</param>
        /// <returns></returns>
        public string GetStepResourceJson(long iid, long wiid)
        {
            string step = WorkFlowHandle.GetStepGroupCtlidByWiid(wiid);
            if (String.IsNullOrEmpty(step))
            {
                step = WorkFlowHandle.GetStepCtlidByWiid(wiid);
            }
            DataTable dt = WorkFlowHandle.GetStepResource(iid, wiid, step);
            return JsonOperation.DataTableToJson(dt);
        }

        /// <summary>
        /// 获取业务的附件资源
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <returns></returns>
        public string GetAttachResourceJson(long iid)
        {
            AttatchmentHelper attHelper = new AttatchmentHelper();
            DataTable dt = attHelper.QueryAttach(iid, "");
            return JsonOperation.DataTableToJson(dt);
        }

        /// <summary>
        /// 获取已办业务的大类类型
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public DataSet GetBusinessTypeHanded(string loginName, string userId)
        {
            DataTable dtTemp = WorkFlowHandle.GetBusinessTypeHanded(loginName, userId);
            DataSet ds = new DataSet();
            ds.Tables.Add(dtTemp);
            return ds;
        }

       /// <summary>
       /// 获取表单id
       /// </summary>
       /// <param name="fid"></param>
       /// <returns></returns>
        public string GetFormLayoutID(string fid)
        {
            string strSql = "select layoutid from moa_form_layout where formid='" + fid + "'";
            try
            {
                IDataAccess ida = SysParams.OAConnection();
                return ida.GetValue(strSql);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="step"></param>
        /// <param name="layoutid"></param>
        /// <returns></returns>
        public string GetFormPermissionJson(string wid, string step, string layoutid)
        {
            string strSql = @"select a.ctl_id,a.ctl_right,b.field_name from moa_form_per a ,moa_form_ds b
                    where a.layoutid = b.layoutid(+) and a.ctl_id = b.ctl_id(+) and a.wid='" + wid + "'"
                + " and a.step='" + step + "'"
                + " and a.layoutid='" + layoutid + "'";
            try
            {
                DataTable dt = new DataTable();
                IDataAccess ida = SysParams.OAConnection();
                ida.RunSql(strSql, out dt);
                return JsonOperation.DataTableToJson(dt, false);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="layoutid"></param>
        /// <param name="iid"></param>
        /// <returns></returns>
        public string GetFormDetailJson(string layoutid, long iid)
        {
            string result = "";
            DataTable dt = new DataTable();
            string strSql = "select wm_concat(field_name || ' as ' || ctl_id) as fields,table_name,query_sql from moa_form_ds where layoutid = '" + layoutid + "' group by table_name ,query_sql";
            try
            {

                IDataAccess ida = SysParams.OAConnection();
                ida.RunSql(strSql, out dt);
                List<String> jsonResult = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    strSql = "select " + dr["fields"] + " from " + dr["table_name"] + " where " + dr["query_sql"];
                    strSql = string.Format(strSql, iid);
                    ida.RunSql(strSql, out dt);
                    if (dt.Rows.Count > 0)
                    {
                        jsonResult.Add(JsonOperation.DataTableRowToJsonInner(dt.Rows[0]));
                    }
                }

                result = "DataTable:[{" + string.Join(",", jsonResult.ToArray()) + "}]";
                result = "{Result:\"" + (jsonResult.Count > 0 ? "True" : "False") + "\"," + result + "}";
                return result;
            }
            catch
            {
                return "";
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="layoutid"></param>
        /// <param name="iid"></param>
        /// <param name="input_index"></param>
        /// <returns></returns>
        public string GetFormDetailJson(string layoutid, long iid, string input_index)
        {
            string result = "";
            DataTable dt = new DataTable();
            string strSql = "select wm_concat(field_name || ' as ' || ctl_id) as fields,table_name,query_sql from moa_form_ds where layoutid = '" + layoutid + "' group by table_name ,query_sql";
            try
            {

                IDataAccess ida = SysParams.OAConnection();
                ida.RunSql(strSql, out dt);
                List<String> jsonResult = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    strSql = "select " + dr["fields"] + " from " + dr["table_name"] + " where " + dr["query_sql"];
                    strSql = string.Format(strSql, iid, input_index);
                    ida.RunSql(strSql, out dt);
                    if (dt.Rows.Count > 0)
                    {
                        jsonResult.Add(JsonOperation.DataTableRowToJsonInner(dt.Rows[0]));
                    }
                }

                result = "DataTable:[{" + string.Join(",", jsonResult.ToArray()) + "}]";
                result = "{Result:\"" + (jsonResult.Count > 0 ? "True" : "False") + "\"," + result + "}";
                return result;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="step"></param>
        /// <param name="userid"></param>
        /// <param name="op"></param>
        /// <param name="viewupdate"></param>
        /// <param name="dosubmit"></param>
        /// <returns></returns>
        public string WorkFlowSaveOfSubmit(long iid, long wiid, string step, string userid, string op, string viewupdate, bool dosubmit)
        {
            string msg = "";
            int iResult = WorkFlowSave(iid, wiid, viewupdate, step, userid, op);
            msg = "{ \"SaveResult\": \"" + (iResult >= 0 ? "True" : "False") + "\"";
            if (dosubmit)
            {
                msg += "," + GetWorkFlowSubmitUser(iid, wiid);
            }
            msg += "}";
            return msg;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="viewupdate"></param>
        /// <param name="dosubmit"></param>
        /// <returns></returns>
        public string WorkFlowSaveOfSubmit(long iid, long wiid, string viewupdate, bool dosubmit)
        {
            string msg = "";
            int iResult = WorkFlowSave(iid, viewupdate);
            msg = "{ \"SaveResult\": \"" + (iResult >= 0 ? "True" : "False") + "\"";
            if (dosubmit)
            {
                msg += "," + GetWorkFlowSubmitUser(iid, wiid);
            }
            msg += "}";
            return msg;
        }

        /// <summary>
        /// 工作流涉及到的表单保存
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="viewUpdate"></param>
        /// <param name="step"></param>
        /// <param name="userid"></param>
        /// <param name="op"></param>
        /// <returns>更新记录数 -1：更新失败</returns>
        private int WorkFlowSave(long iid, long wiid, string viewUpdate, string step, string userid, string op)
        {

            int iResult = -1;
            IDataAccess ida = SysParams.OAConnection();
            try
            {


                iResult = SendOfficialOP(iid, wiid, step, userid, op, ref ida);
                if (iResult <= 0)
                {
                    return iResult;
                }

                DataTable dt = new DataTable();
                string strSql = "";
                if (!string.IsNullOrEmpty(viewUpdate))
                {
                    XmlDocument xDoc = JsonOperation.Json2Xml(viewUpdate);
                    foreach (XmlElement viewElem in xDoc.DocumentElement.ChildNodes)
                    {
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        XmlNode xmlWhere = viewElem.SelectSingleNode("where");
                        XmlNode xmlFields = viewElem.SelectSingleNode("fields");
                        foreach (XmlElement ctlElem in xmlFields.ChildNodes)
                        {
                            dic.Add(ctlElem.Name, ctlElem.InnerText);
                        }

                        String formid = viewElem.Name;
                        strSql = @"select wm_concat(FIELD_NAME) as FIELDS,TABLE_NAME,QUERY_SQL from moa_form_ds where 
                            layoutid = (select Layoutid from moa_form_layout where Formid = '" + formid + "') group by TABLE_NAME,QUERY_SQL";
                        ida.RunSql(strSql, out dt);
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            String[] fields = dt.Rows[i]["FIELDS"].ToString().Split(',');
                            bool doUpdate = false;
                            foreach (String field in fields)
                            {
                                if (dic.ContainsKey(field))
                                {
                                    doUpdate = true;
                                }
                            }
                            if (doUpdate)
                            {
                                String tableName = dt.Rows[i]["TABLE_NAME"].ToString();
                                String querySQL = dt.Rows[i]["QUERY_SQL"].ToString();

                                strSql = "UPDATE " + tableName + " SET ";

                                foreach (String field in fields)
                                {
                                    if (dic.ContainsKey(field))
                                    {

                                        String strFieldTypeSql = @"SELECT data_type
                                            FROM all_tab_cols
                                            WHERE table_name = '" + tableName + "' and column_name ='" + field + "'";
                                        String strFieldType = ida.GetValue(strFieldTypeSql);

                                        if (strFieldType.Equals("DATE"))
                                        {
                                            strSql += field + " = TO_DATE(" + dic[field] + ",'yyyy-MM-dd hh24:mi:ss'),";
                                        }
                                        else
                                        {
                                            strSql += field + " = '" + dic[field] + "',";
                                        }
                                    }
                                }
                                strSql = strSql.Remove(strSql.Length - 1);
                                strSql += " WHERE " + querySQL;
                                strSql = String.Format(strSql, iid, xmlWhere.InnerText);
                            }
                        }

                        iResult += ida.RunSql(strSql);
                    }
                }

                iResult += 1;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                ida.Close(false);
            }
            return iResult;
        }

        /// <summary>
        /// 工作流涉及到的表单保存
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="viewUpdate"></param>
        /// <returns>更新记录数 -1：更新失败</returns>
        private int WorkFlowSave(long iid, string viewUpdate)
        {

            int iResult = -1;
            try
            {
                XmlDocument xDoc = JsonOperation.Json2Xml(viewUpdate);
                IDataAccess ida = SysParams.OAConnection();

                DataTable dt = new DataTable();
                string strSql = "";
                foreach (XmlElement viewElem in xDoc.DocumentElement.ChildNodes)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    XmlNode xmlWhere = viewElem.SelectSingleNode("where");
                    XmlNode xmlFields = viewElem.SelectSingleNode("fields");
                    foreach (XmlElement ctlElem in xmlFields.ChildNodes)
                    {
                        if (ctlElem.HasChildNodes && ctlElem.ChildNodes.Count > 1)
                        {
                            foreach (XmlElement ctl in ctlElem.ChildNodes)
                            {
                                dic.Add(ctl.Name, ctl.InnerText);
                            }
                        }
                        else
                        {
                            dic.Add(ctlElem.Name, ctlElem.InnerText);
                        }
                    }

                    String formid = viewElem.Name;
                    strSql = @"select wm_concat(FIELD_NAME) as FIELDS,TABLE_NAME,QUERY_SQL from moa_form_ds where 
                    layoutid = (select Layoutid from moa_form_layout where Formid = '" + formid + "') group by TABLE_NAME,QUERY_SQL";
                    ida.RunSql(strSql, out dt);
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        String[] fields = dt.Rows[i]["FIELDS"].ToString().Split(',');
                        String tableName = dt.Rows[i]["TABLE_NAME"].ToString();
                        String querySQL = dt.Rows[i]["QUERY_SQL"].ToString();
                        strSql = "UPDATE " + tableName + " SET ";
                        foreach (String field in fields)
                        {
                            if (dic.ContainsKey(field))
                            {
                                strSql += field + " = '" + dic[field] + "',";
                            }
                        }
                        strSql = strSql.Remove(strSql.Length - 1);
                        strSql += " WHERE " + querySQL;
                        strSql = String.Format(strSql, iid, xmlWhere.InnerText);
                    }
                    iResult += ida.RunSql(strSql);
                }

                iResult += 1;
            }
            catch (Exception ex)
            {
                throw;
            }
            return iResult;
        }


        /// <summary>
        /// 工作流涉及到的表单保存
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="viewUpdate"></param>
        /// <returns>流向，用户列表</returns>
        private string GetWorkFlowSubmitUser(long iid, long wiid)
        {
            string sResult = "";

            try
            {
                string wid = WorkFlowHandle.GetWidByIid(iid);
                string wname = WorkFlowHandle.GetWnameByWid(wid);
                string step = WorkFlowHandle.GetStepByWiid(wiid);
                // string stepCtlid = WorkFlowHandle.GetStepCtlidByWiid(wiid);
                string stepCtlid = WorkFlowHandle.GetStepGroupCtlidByWiid(wiid);
                if (String.IsNullOrEmpty(stepCtlid))
                {
                    stepCtlid = WorkFlowHandle.GetStepCtlidByWiid(wiid);
                }
                DataTable dt = WF_Business.WorkFlowStep.GetNextStepByStep(wid, stepCtlid, iid, wiid);

                if (dt.Rows.Count > 0)
                {
                    string sflow = "SendTo:[";
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        int steptype = (int)WF_Business.WorkFlowStep.GetStepType(iid, dt.Rows[i]["FNAME"].ToString(), dt.Rows[i]["ENAME"].ToString());
                        sflow += "{\"fname\":\"" + dt.Rows[i]["FNAME"].ToString() + "\",";
                        sflow += "\"ename\":\"" + dt.Rows[i]["ENAME"].ToString() + "\",";
                        sflow += "\"step_type\":\"" + steptype + "\",";
                        sflow += "\"extend_type\":\"" + dt.Rows[i]["EXTEND_TYPE"].ToString() + "\",";
                        DataTable dtUsers = GetNextStepGroupUsers(iid, wiid, dt.Rows[i]["FNAME"].ToString());
                        dtUsers.TableName = "users";
                        sflow += JsonOperation.DataTableToJsonInner(dtUsers) + "},";
                    }

                    sflow = sflow.Remove(sflow.Length - 1) + "]";
                    sResult += sflow;
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return sResult;
        }

        /// <summary>
        /// 获取当前节点的用户id
        /// </summary>
        /// <param name="wiid">节点id</param>
        /// <returns></returns>
        protected string GetCurrentUserid(long wiid)
        {
            string strSql = "select userid from st_work_item where wiid='" + wiid + "'";
            try
            {
                IDataAccess ida = SysParams.OAConnection();
                return ida.GetValue(strSql);
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取流程的岗位用户列表
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="flow"></param>
        /// <returns></returns>
        private DataTable GetNextStepGroupUsers(long iid, long wiid, string flow)
        {
            string userid = GetCurrentUserid(wiid);
            List<string> listGroupFilter = null;
            DataTable dtRoles = GetRoleList(wiid, iid, flow);
            if (dtRoles != null)
            {
                listGroupFilter = new List<string>();
                foreach (DataRow dr in dtRoles.Rows)
                {
                    listGroupFilter.Add("\'" + dr[0].ToString() + "\'");
                }
            }
            string strGroupFilter = "";
            if (listGroupFilter != null)
            {
                strGroupFilter = String.Join(",", listGroupFilter.ToArray());
            }
            string wid = WF_Business.WorkFlowResource.GetWidByIID(iid.ToString());
            string strSql = @"select a.userid,a.user_name,b.groupid,b.group_name,d.depart_name,d.order_id,a.orderbyid from st_user a, st_group b,st_user_department m,
                st_department d,(Select userid,gid From st_user_group Where gid In
                (Select gid From st_group_in_step Where wid='{0}' And stpname In
                (Select ename from st_flow Where wid='{0}' And fname='{1}'))) c
                where c.userid = a.userid(+) and c.gid = b.groupid and a.userid=m.userid and m.order_id = d.departid";
            if (!String.IsNullOrEmpty(strGroupFilter))
            {
                strSql += " and b.group_name in (" + strGroupFilter + ")";
            }
            strSql = string.Format(strSql, wid, flow);

            if (flow == "岗位内提交") //如果是特殊的流向（岗位内提交），则例外处理
            {
                string stpGroup = WorkFlowHandle.GetStepGroupCtlidByWiid(wiid);
                string stpName = WorkFlowHandle.GetStepCtlidByWiid(wiid);
                if (string.IsNullOrEmpty(stpGroup))
                {
                    strSql = @"Select a.userid, a.user_name, b.groupid, b.group_name, d.depart_name,d.order_id,a.orderbyid from st_user a, st_group b, st_department d,st_user_department m, (select c.userid, c.gid from st_user_group c  where c.gid in (select gid from st_group_in_step Where wid = '{0}' and stpname = '{1}')) c  Where c.gid = b.groupid(+) and c.userid = a.userid(+) and a.userid=m.userid and m.order_id = d.departid and c.userid <> '{2}'";

                    strSql = string.Format(strSql, wid, stpName, userid);
                }
                else
                {
                    strSql = @"Select a.userid, a.user_name, b.groupid, b.group_name, d.depart_name,d.order_id,a.orderbyid from st_user a, st_group b, st_department d,st_user_department m, (select c.userid, c.gid from st_user_group c  where c.gid in (select gid from st_group_in_step Where wid = '{0}' and stpname = '{1}')) c  Where b.gid in (select groupid from st_group Where group_name = '{2}') and c.gid = b.groupid(+) and c.userid = a.userid(+) and a.userid=m.userid and m.order_id = d.departid and c.userid <> '{3}'";
                    strSql = string.Format(strSql, wid, stpGroup, stpName, userid);
                }
            }

            strSql += " Order By sort,order_id,orderbyid";
            DataTable dtTemp = new DataTable();
            //IDataAccess ida = SysParams.OAConnection();
            IDataAccess ida = WF_Business.SysParams.OAConnectionWithEnterprise(false);
            ida.RunSql(strSql, out dtTemp);

            return dtTemp;
        }

        public DataTable GetRoleList(long wiid, long iid, string flow)
        {
            DataTable dtResult = null;
            IDataAccess ida = SysParams.OAConnection();
            string sql = "select t.stepctlid,t.stepgroupctlid from st_work_item t where wiid='" + wiid + "'";
            DataTable dtStep = new DataTable();
            ida.RunSql(sql, out dtStep);
            string nowStep = string.Empty;
            if (dtStep.Rows.Count > 0)
            {
                nowStep = dtStep.Rows[0]["stepgroupctlid"].ToString();
                if (string.IsNullOrEmpty(nowStep))
                    nowStep = dtStep.Rows[0]["stepctlid"].ToString();
            }
            WF_Business.StepType stepType = WF_Business.WorkFlowStep.GetStepType(iid, flow, nowStep);
            if (stepType == WF_Business.StepType.End)
            {
                return null;
            }
            if (stepType == WF_Business.StepType.EndNotAccept)
            {
                return null;
            }
            if (stepType == WF_Business.StepType.EndNotTransact)
            {
                return null;
            }
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            dtResult = WorkFlowHandle.GetRolesInStep(iid, wiid, flow);
            return dtResult;
        }


        /// <summary>
        /// 流程提交方法
        /// </summary>
        /// <param name="iid"></param>
        /// <param name="wiid"></param>
        /// <param name="fname">流程名称</param>
        /// <param name="ename">流程节点名称</param>
        /// <param name="users">用户组用户ID集合</param>
        /// <returns></returns>
        public string WorkFlowSubmit(long iid, long wiid, string fname, string ename, string users)
        {
            string msg = "";
            XmlDocument xDoc = JsonOperation.Json2Xml("{users:" + users + "}");
            List<string> stages = new List<string>();
            XmlNode xmlUsers = xDoc.DocumentElement.FirstChild;
            ArrayList arrList = new ArrayList();
            List<WF_Business.FlowUserStruct> listUserStruct = new List<WF_Business.FlowUserStruct>();
            foreach (XmlElement viewElem in xmlUsers.ChildNodes)
            {
                WF_Business.FlowUserStruct fus = new WF_Business.FlowUserStruct();
                fus.FlowName = fname;
                fus.StepName = viewElem.Name;
                stages.Add(viewElem.Name);
                fus.IsRound = false;
                List<string> listUsers = new List<string>();
                foreach (XmlNode xnode in viewElem.SelectNodes("Item"))
                {
                    listUsers.Add(xnode.InnerText);
                }
                fus.Users = listUsers.ToArray();
                listUserStruct.Add(fus);
            }

            string step = WorkFlowHandle.GetStepByWiid(wiid);
            bool result = false;
            if (listUserStruct.Count > 0)
            {
                result = new WF_Business.WorkItem().Sumbit(iid, wiid, listUserStruct.ToArray(), ref msg);
            }
            else
            {
                result = new WF_Business.WorkItem().Sumbit(iid, wiid, fname, null, ref msg);
            }

            WorkFlowHandle.AloneFlowHandle2(iid.ToString(), wiid.ToString(), step);

            msg = "{ \"Result\": \"" + (result ? "True" : "False") + "\",\"message\":\"" + msg + "\"}";

            return msg;
        }

        /// <summary>
        /// 获取公文的意见列表
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public DataTable GetOfficialOPByIID(long iid, long wiid, string step)
        {
            DataTable dtResult = null;
            IDataAccess ida = SysParams.OAConnection();
            string sql = @"select s.user_name as username,t.IID ,t.STEP,t.USERID,t.OP,to_char(t.OP_DATE,'yyyy-MM-dd')  OP_DATE
                from moa_official_op t,st_user s
                where t.userid = s.userid(+) and t.iid='" + iid + "' and t.wiid='" + wiid + "' order by t.op_index asc";
            ida.RunSql(sql, out dtResult);
            return dtResult;
        }

        /// <summary>
        /// 添加公文的意见列表
        /// </summary>
        /// <param name="iid">业务编号</param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public int SendOfficialOP(long iid, long wiid, string step, string userid, string opText, ref IDataAccess ida)
        {

            int iResult = -1;

            try
            {
                string sql = String.Format("select decode(max(op_index),null,1,max(op_index)+1) op_index from moa_official_op where iid = '{0}'", iid);
                string op_index = ida.GetValue(sql);
                sql = String.Format("select count(1) from moa_official_op where iid = '{0}' and userid='{1}' and step = '{2}' and wiid = '{3}'", iid, userid, step, wiid);
                bool bOpExsit = ida.GetValue(sql) != "0";
                if (!bOpExsit)
                {
                    sql = String.Format(@"INSERT INTO MOA_OFFICIAL_OP
                        (IID,WIID,STEP,USERID,OP,OP_DATE,OP_INDEX)
                            VALUES
                        ('{0}','{1}','{2}','{3}','{4}',to_date('{5}','yyyy-MM-dd'),{6})",
                            iid, wiid, step, userid, opText, DateTime.Now.ToString("yyyy-MM-dd"), op_index);
                }
                else
                {
                    sql = String.Format(@"UPDATE MOA_OFFICIAL_OP
                            SET OP = '{0}',OP_DATE = to_date('{1}','yyyy-MM-dd')
                            WHERE IID='{2}' AND WIID='{3}' AND USERID = '{4}'",
                            opText, DateTime.Now.ToString("yyyy-MM-dd"), iid, wiid, userid);
                }
                iResult = ida.RunSql(sql);

                IDataAccess idaMOA = SysParams.OAConnection(true);
                try
                {
                    IDataParameter[] idParms = DataFactory.GetParameter(DatabaseType.Oracle, 4);
                    idParms[0] = new OracleParameter("inIID", OracleType.VarChar);
                    idParms[1] = new OracleParameter("inStep", OracleType.VarChar);
                    idParms[2] = new OracleParameter("inUserID", OracleType.VarChar);
                    idParms[3] = new OracleParameter("inOPText", OracleType.VarChar, 4000);

                    idParms[0].Value = iid;
                    idParms[1].Value = step;
                    idParms[2].Value = userid;
                    idParms[3].Value = opText;

                    idaMOA.RunProc("NJGT_MOA.Update_MOAOP", ref idParms);
                    idaMOA.Close(true);
                }
                catch (Exception err)
                {
                    idaMOA.Close(false);
                    throw new Exception("保存失败=>" + err.Message);
                }

            }
            catch (Exception ex)
            {
                iResult = -99;
            }

            return iResult;
        }

    }
}